/**
 * Author: zhjpaul
 * Description: 用于与Flask后台进行数据的交互
 */

/**
 * 用于在界面中提示操作结果
 * @param  {String} message 提示信息
 * @return {void}
 */
 function info(message) {
    
    $("#operation-information").show();
    $("#operation-information").text(message);
    setTimeout(function () {
        $("#operation-information").hide();
    }, 2000);

 }

/**
 * 获取交换机所有物理端口信息
 * 
 * @return {void}
 */

function getPhyPortsStatus(renderSwitchPhyPort, attachEventToPort) {

    $.get(CONFIG.URL.GetPhyPortsStatus, function (data) {

        if ('phy_ports' in data) {

            gPhyPortsStatus = data['phy_ports'];

            for (var i = 0, len = gPhyPortsStatus.length; i < len; i += 2) {
                renderSwitchPhyPort(i, gPhyPortsStatus[i]['phy_tap_flag'], gPhyPortsStatus[i]['phy_port_alias']); 
            }

            for (var i = 1, len = gPhyPortsStatus.length; i < len; i += 2) {
                renderSwitchPhyPort(i, gPhyPortsStatus[i]['phy_tap_flag'], gPhyPortsStatus[i]['phy_port_alias']); 
            }
            
            attachEventToPort();

            showPortTraffic(0);
        }
    })

}

/**
 * 更新交换机某个物理端口信息
 * 
 * @param  {Array} portStatus  交换机端口信息
 * @return {void}
 */

function updatePhyPortStatus(portStatus) {

    $.ajax(CONFIG.URL.UpdatePhyPortStatus, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(portStatus),
        success: function (data) {
            info("update port status successfully!!!");
        }
    });

}

/**
 * 获取交换机上所有LAG端口的信息
 * 
 * @return {void}
 */

function getLAGPortsStatus() {

    $.get(CONFIG.URL.GetLAGPortsStatus, function (data) {

        if ('lag_ports' in data) {

            gLAGPortsStatus = data['lag_ports'];
            for (var i = 0, len = gLAGPortsStatus.length; i < len; i++) {
                renderLAG(gLAGPortsStatus[i]);
            }
        }

    });

}

/**
 * 更新某个LAG端口的信息，一旦这个LAG端口上没有任何包含的物理端口时删除此LAG端口
 *  
 * @param  {Object} lagInfo 用于描述一个LAG端口
 * @return {void}
 */

function updateLAGPortStatus(lagInfo) {

    $.ajax(CONFIG.URL.UpdateLAGPortStatus, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(lagInfo),
        success: function (data) {
            info("update LAG port successfully!!!");
        }
    });

}

/**
 * 获取端口的流量信息
 * @param  {Object} portInfo 描述获取哪个端口的信息
 * @return {void}
 */

function getPortTrafficStat(portInfo) {

    $.ajax(CONFIG.URL.GetPortTrafficStat, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(portInfo),
        success: function (data) {

            if ('outport_traffic_stats' in data) {

                var traffic = data['outport_traffic_stats'],
                    pieData = [];

                // 初始化Traffic表格
                $("#table tbody").html('');

                for (var i = 0, len = traffic.length; i < len; i++) {

                    var line = []
                        id = parseInt(traffic[i]['outport_id']),
                        trafficInfo = {
                            'outport': gPhyPortsStatus[id]['phy_port_alias'],
                            'traffic': traffic[i]['outport_traffic'],
                            'tapPort': parseInt(traffic[i]['tapped_port_id'])
                        };

                    renderTrafficTable(trafficInfo);

                    line.push(gPhyPortsStatus[id]['phy_port_alias']);
                    line.push(parseFloat(traffic[i]['traffic_percent']));

                    pieData.push(line);
                }

                drawPie(pieData);
            }
        }
    });

}

/**
 * 获取当前所有流表项信息
 * 
 * @return {void}
 */

function getFlowEntries() {

    $.get(CONFIG.URL.GetFlowEntries, function (data) {

        if ('flow_entries' in data) {

            var flowEntries = data['flow_entries'];
            for (var i = 0, len = flowEntries.length; i < len; i++) {
                gFlowEntries[flowEntries[i]['flow_id']] = flowEntries[i];
                renderFlowEntry(flowEntries[i]);
            }
        }

    });

}

/**
 * 添加流表项
 * 
 * @param {Object} flowEntry 流表项各字段数据
 * @return {void}
 */

function addFlowEntry(flowEntry) {

    console.log(flowEntry)

    $.ajax(CONFIG.URL.AddFlowEntry, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(flowEntry),
        success: function (data) {
            info("add flow entry successfully!!!");
            flowEntry['flow_id'] = data['flow_id'];
            renderFlowEntry(flowEntry);
        }
    });

}

/**
 * 修改流表项
 * 
 * @param  {Object} flowEntry 流表项各字段数据
 * @return {void}
 */

function modifyFlowEntry(flowEntry) {

    flowEntry['target_flow_id'] = flowEntry['flow_id'];

    $.ajax(CONFIG.URL.ModifyFlowEntry, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(flowEntry), 
        success: function (data) {
            info("modify flow entry successfully!!!");
        }
    });

}

/**
 * 删除流表项
 * 
 * @param  {Object} flowID 流表项ID
 * @return {void}
 */

function deleteFlowEntry(flowID) {

    $.ajax(CONFIG.URL.DeleteFlowEntry, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(flowID), 
        success: function (data) {
            info("delete flow entry successfully!!!");
        }
    });

}

/**
 * 获取当前所有组表信息
 * 
 * @return {void}
 */

function getGroupTables() {

    $.get(CONFIG.URL.GetGroupTables, function (data) {

        if ('group_tables' in data) {

            var groupTables = data['group_tables'];

            for (var i = 0, len = groupTables.length; i < len; i++) {
                renderGroupTable(groupTables[i]);
            }
        }
    });
}

/**
 * 添加组表

 * @param  {void} groupTableInfo 组表信息
 * @return {void}
 */

function addGroupTable(groupTableInfo) {

    $.ajax(CONFIG.URL.AddGroupTable, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(groupTableInfo),
        success: function (data) {
            info("add group table successfully!!!");
            renderGroupTable(groupTableInfo);
        }
    })

}

/**
 * 修改组表

 * @param  {void} groupTableInfo 组表信息
 * @return {void}
 */

function modifyGroupTable(groupTableInfo) {

    $.ajax(CONFIG.URL.ModifyGroupTable, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(groupTableInfo),
        success: function (data) {
            info("modify group table successfully!!!");
        }
    });

}

/**
 * 删除组表
 * 
 * @param  {Object} groupID 组表ID
 * @return {void}
 */

function deleteGroupTable(groupID) {

    $.ajax(CONFIG.URL.DeleteGroupTable, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(groupID), 
        success: function (data) {
            info("delete group table successfully!!!");
        }
    });

}


/**
 * 获取当前所有逻辑组信息
 * 
 * @return {void}
 */

function getLogicGroups() {

    $.get(CONFIG.URL.GetLogicGroups, function (data) {

        if ('logic_groups' in data) {

            var logicGroups = data['logic_groups'];
            for (var i = 0, len = logicGroups.length; i < len; i++) {
                console.log(logicGroups[i])
                renderLogicGroup(logicGroups[i]);
            }
        }

    });

}

/**
 * 更新逻辑组信息
 *  
 * @param  {Object} logicGroupInfo 用于描述一个逻辑组
 * @return {void}
 */

function updateLogicGroup(logicGroupInfo) {

    $.ajax(CONFIG.URL.UpdateLogicGroup, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(logicGroupInfo),
        success: function (data) {
            info("update logic group successfully!!!");
        }
    });

}


/**
 * 配置控制器
 * 
 * @param  {Object} controllerInfo 控制器信息（名字，ip与端口）
 * @return {void}
 */

function configController(controllerInfo) {
    console.log(controllerInfo)
    $.ajax(CONFIG.URL.ConfigController, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(controllerInfo), 
        success: function (data) {
            info("update controller information successfully!!!");
        }
    })
}

/**
 * 获取交换机实时流量信息
 *
 * @param  {Object} flowInfo 需要获取实时流量的流表项信息（flow_id）
 * @return {void}
 */

function getRealTimeTraffic(flowInfo) {

    $.ajax(CONFIG.URL.RealTimeTraffic, {
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(flowInfo),
        success: function (data) {
            if ("flow_traffic" in data) {
                drawLineChart(data['flow_traffic']);
            }
            info("get real time trafiic info")
        }
    })
}